package com.ayoka.parenting.ui.live.liveclassroom;

import android.app.Activity;
import android.content.DialogInterface;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ayoka.parenting.R;
import com.ayoka.parenting.bean.BaseResponse;
import com.ayoka.parenting.bean.BasicUserInfoBean;
import com.ayoka.parenting.bean.ChatMessageBean;
import com.ayoka.parenting.bean.DiscussGroupBean;
import com.ayoka.parenting.bean.DiscussGroupTempRoomBean;
import com.ayoka.parenting.bean.GrownClassroomDetailBean;
import com.ayoka.parenting.bean.UserManager;
import com.ayoka.parenting.interf.SimpleRequestCallback;
import com.ayoka.parenting.interf.SimpleTICCallback;
import com.ayoka.parenting.interf.SimpleWhiteBoardCallback;
import com.ayoka.parenting.mvp.BasePresenterImpl;
import com.ayoka.parenting.ui.live.ChatDialog;
import com.ayoka.parenting.ui.live.WhiteBoardDialog;
import com.jincp.common.brvah.BaseQuickAdapter;
import com.jincp.common.brvah.BaseViewHolder;
import com.jincp.common.brvah.layoutmanager.MyLinearLayoutManager;
import com.jincp.common.dialog.DialogDismissListener;
import com.jincp.common.dialog.DialogHelper;
import com.jincp.common.dialog.DialogResultListener;
import com.jincp.common.popup.CommonPopupWindow;
import com.jincp.common.popup.PopupDismissListener;
import com.jincp.common.utils.LiveDataBus;
import com.jincp.common.utils.MyLogger;
import com.jincp.common.utils.UIUtils;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.teduboard.TEduBoardController;
import com.tencent.ticsdk.core.TICClassroomOption;
import com.tencent.ticsdk.core.TICManager;
import com.tencent.trtc.TRTCCloudDef;

import java.util.List;

/**
 * @ProjectName: MVPPlugin.
 * @ClassName: LiveClassroomPresenter.
 * @Description: .
 * @Author: jincp.
 * @CreateDate: 2019/10/10 18:17.
 */
public class LiveClassroomPresenter extends BasePresenterImpl<LiveClassroomContract.View> implements LiveClassroomContract.Presenter {

    private LiveClassroomModel model;

    public LiveClassroomPresenter() {
        model = new LiveClassroomModel();
    }

    @Override
    public void enterLiveRoom(String scheduleId) {
        mView.get().showWaitDialog("正在初始化房间...");
        model.enterLiveRoom(this, scheduleId, new SimpleRequestCallback<GrownClassroomDetailBean>() {
            @Override
            public void onSuccess(GrownClassroomDetailBean data) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().configLiveRoomDetailData(data);
            }

            @Override
            public void onFailure(int errCode, String errMsg) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().showToast(errMsg);
                mView.get().configLiveRoomDetailData(null);
            }
        });
    }

    @Override
    public List<String> getCourseStepList() {
        return model.getCourseStepList();
    }

    @Override
    public void joinLiveRoom(final int roomId, final int role) {
        MyLogger.d(TAG, "joinLiveRoom");
        setTRTCCloudParam();
        //1、设置白板的回调
        SimpleWhiteBoardCallback whiteBoardCallback = new SimpleWhiteBoardCallback(mView);
        //2、如果用户希望白板显示出来时，不使用系统默认的参数，就需要设置特性缺省参数，如是使用默认参数，则填null。
        TEduBoardController.TEduBoardInitParam initParam = new TEduBoardController.TEduBoardInitParam();
        initParam.brushColor = new TEduBoardController.TEduBoardColor(0, 255, 0, 255);
        initParam.smoothLevel = 0; //用于指定笔迹平滑级别，默认值0.1，取值[0, 1]

        TICClassroomOption classroomOption = new TICClassroomOption();
        classroomOption.classId = roomId;
        classroomOption.ROLE = role;
        classroomOption.APP_SCENE = TRTCCloudDef.TRTC_APP_SCENE_LIVE;

        classroomOption.boardCallback = whiteBoardCallback;
        classroomOption.boardInitPara = initParam;

        TICManager.getInstance().joinClassroom(classroomOption, new SimpleTICCallback() {
            @Override
            public void onSuccess(Object data) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().onJoinLiveRoomCallback(true);
                loadMoreMessage(null);
                getGroupMemberList(roomId);
            }

            @Override
            public void onFailure(int errorCode, String errorMessage) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                if (errorCode == 6014) {
                    joinLiveRoom(roomId, role);
                } else if (errorCode == 10015) {
//                        mViewRef.get().showToast("课堂不存在:" + roomId + " err:" + errorCode + " msg:" + errorMessage);
                    mView.get().onJoinLiveRoomCallback(false);
                } else {
//                        mViewRef.get().showToast("进入课堂失败:" + roomId + " err:" + errorCode + " msg:" + errorMessage);
                    mView.get().onJoinLiveRoomCallback(false);
                }
            }
        });
    }

    private void getGroupMemberList(long roomId) {
//        TICManager.getInstance().getGroupMemberList(String.valueOf(roomId), new TICManager.TICCallback<List<TIMGroupMemberInfo>>() {
//            @Override
//            public void onSuccess(List<TIMGroupMemberInfo> data) {
//                for (TIMGroupMemberInfo timGroupMemberInfo : data) {
//                    model.getMemberByUserId(timGroupMemberInfo.getUser(), true);
//                }
//                if (!isAttached()) return;
//                mView.get().configOnlineMemberList(model.getMemberList());
//            }
//
//            @Override
//            public void onError(String module, int errCode, String errMsg) {
//                Log.d(TAG, errMsg);
//            }
//        });
    }


    @Override
    public void loadMoreMessage(TIMMessage message) {
        TICManager.getInstance().getMessageList(20, message, new TICManager.TICCallback<List<TIMMessage>>() {
            @Override
            public void onSuccess(List<TIMMessage> timMessages) {
                formatChatMessageList(timMessages);
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                MyLogger.e(TAG, "message error" + errMsg);
            }
        });
    }

    @Override
    public void getScheduleTempSubRoom(String scheduleId) {
        model.getScheduleTempSubRoom(this, scheduleId, new SimpleRequestCallback<BaseResponse<DiscussGroupTempRoomBean>>() {
            @Override
            public void onSuccess(BaseResponse<DiscussGroupTempRoomBean> data) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().configScheduleTempSubRoom(data.data);
            }

            @Override
            public void onFailure(int errCode, String errMsg) {
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().showToast(errMsg);
                mView.get().configScheduleTempSubRoom(null);
            }
        });
    }

    @Override
    public void saveChatMessage(String userId, boolean isChatToSelf, String content, String operation, TIMMessage message) {
        BasicUserInfoBean userBean = model.getMemberByUserId(userId, true);
        ChatMessageBean chatMessageBean = new ChatMessageBean(userBean, content, message);
        chatMessageBean.isChatToSelf = isChatToSelf;
        model.saveChatMessage(chatMessageBean);
        LiveDataBus.getInstance().with("ChatMessage", String.class).postValue("Send");
    }

    @Override
    public void quitLiveRoom(boolean cleanBoard, final DiscussGroupBean discussGroupBean) {
        MyLogger.d(TAG, "quitLiveRoom");
        mView.get().showWaitDialog(UIUtils.getString(R.string.loading));
        TICManager.getInstance().quitClassroom(cleanBoard, new TICManager.TICCallback() {
            @Override
            public void onSuccess(Object data) {
                MyLogger.d(TAG, "onSuccess");
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().onQuitLiveRoomCallback(true, discussGroupBean == null);
                if (discussGroupBean != null) {
                    createDiscussGroupRoom(discussGroupBean.SubRoomID, discussGroupBean.ScheduleID);
                }
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                MyLogger.d(TAG, "onError" + errMsg);
                if (!isAttached()) return;
                mView.get().hideWaitDialog();
                mView.get().onQuitLiveRoomCallback(false, discussGroupBean == null);
                if (discussGroupBean != null) {
                    createDiscussGroupRoom(discussGroupBean.SubRoomID, discussGroupBean.ScheduleID);
                }
            }
        });
    }

    @Override
    public void showExitDialog(Activity activity) {
        DialogHelper.getOkCancelDialog(activity, "提示", "确定要退出本次课程直播吗？", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                quitLiveRoom(false, null);
            }
        }).show();
    }

    @Override
    public void showWhiteBoardDialog(FragmentManager fragmentManager) {
        WhiteBoardDialog dialog = new WhiteBoardDialog.Builder()
                .setGravity(Gravity.BOTTOM)
                .setSize(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .build();
        dialog.setDialogDismissListener(new DialogDismissListener() {
            @Override
            public void dismiss(DialogFragment dialog) {
                if (!isAttached()) return;
                mView.get().onDialogDismiss(dialog);
            }
        });
        dialog.show(fragmentManager, "WhiteBoardDialog");
    }

    @Override
    public void showChatMessageDialog(FragmentManager fragmentManager) {
        ChatDialog dialog = new ChatDialog.Builder()
                .setGravity(Gravity.BOTTOM)
                .setSize(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .build();
        dialog.setDialogDismissListener(new DialogDismissListener() {
            @Override
            public void dismiss(DialogFragment dialog) {
                if (!isAttached()) return;
                mView.get().onDialogDismiss(dialog);
            }
        });
        dialog.setMessageProvider(new ChatDialog.MessageProvider() {
            @Override
            public List<BasicUserInfoBean> getUserBeanList() {
                return model.getMemberList();
            }

            @Override
            public List<ChatMessageBean> getChatMessageList() {
                return model.getChatMessageList();
            }

            @Override
            public void loadMoreMessage(TIMMessage message) {
                LiveClassroomPresenter.this.loadMoreMessage(message);
            }
        });
        dialog.setDialogResultListener(new DialogResultListener() {
            @Override
            public void result(DialogFragment dialogFragment, Object result) {
                if (!isAttached()) return;
                String[] data = (String[]) result;
                if (data.length > 1) {
                    if (data[0].equals("sendGroupTextMessage")) {
                        LiveClassroomPresenter.this.sendGroupTextMessage(data[1]);
                    } else if (data[0].equals("sendTextMessage")) {
                        LiveClassroomPresenter.this.sendTextMessage(data[1], data[2]);
                    }
                }
            }
        });
        dialog.show(fragmentManager, "ChatDialog");
    }

    @Override
    public void showCourseStepPopup(final Activity activity, View view, final String courseTitle, final int currentStep) {
        CommonPopupWindow popupWindow = new CommonPopupWindow.Builder(activity)
                //设置PopupWindow布局
                .setView(R.layout.popup_course_step)
                .setAnimationStyle(R.anim.slide_in_top)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setPopupDismissListener(new PopupDismissListener() {
                    @Override
                    public void dismiss(PopupWindow popupWindow) {
                        if (!isAttached()) return;
                        mView.get().onPopupDismiss(popupWindow);
                    }
                })
                //设置PopupWindow里的子View及点击事件
                .setCreateViewCallback(new CommonPopupWindow.ViewInterface() {
                    @Override
                    public void getChildView(PopupWindow popupWindow, View view, int layoutResId) {
                        TextView tvCourseName = view.findViewById(R.id.tv_course_name);
                        tvCourseName.setText(courseTitle);
                        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
                        recyclerView.setLayoutManager(new MyLinearLayoutManager(activity));
                        BaseQuickAdapter adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_course_step, getCourseStepList()) {
                            @Override
                            protected void convert(BaseViewHolder holder, String item) {
                                holder.setText(R.id.tv_step, item)
                                        .setText(R.id.tv_status, "正在进行")
                                        .setVisible(R.id.tv_status, currentStep == holder.getAdapterPosition())
                                        .setTextColor(R.id.tv_step, currentStep == holder.getAdapterPosition() ? UIUtils.getColor(R.color.colorPrimary) : UIUtils.getColor(R.color.white))
                                        .setTextColor(R.id.tv_status, currentStep == holder.getAdapterPosition() ? UIUtils.getColor(R.color.colorPrimary) : UIUtils.getColor(R.color.white));
                                if (currentStep == holder.getAdapterPosition()) {
                                    holder.setBackgroundColor(R.id.layout_current_stage, UIUtils.getColor(R.color.white_alpha_32));
                                }
                            }
                        };
                        recyclerView.setAdapter(adapter);
                    }
                })
                //开始构建
                .create();
        //弹出PopupWindow
        popupWindow.showAsDropDown(view, 0, -view.getHeight());
    }

    private void createDiscussGroupRoom(final int roomId, final String scheduleId) {
        MyLogger.d(TAG, "createDiscussGroupRoom");
        TICManager.getInstance().createClassroom(roomId, new SimpleTICCallback() {
            @Override
            public void onSuccess(Object data) {
                if (!isAttached()) return;
//                    mViewRef.get().showToast("创建课堂 成功, 房间号："  + mRoomId);
                mView.get().createDiscussGroupRoomCallback(true, roomId, scheduleId);
            }

            @Override
            public void onFailure(int errorCode, String errorMessage) {
                if (!isAttached()) return;
                if (errorCode == 6014) {
                    createDiscussGroupRoom(roomId, scheduleId);
                } else if (errorCode == 10021) {
//                        mViewRef.get().showToast("该课堂已被他人创建，请\"加入课堂\"");
                    mView.get().createDiscussGroupRoomCallback(true, roomId, scheduleId);
                } else if (errorCode == 10025) {
//                        mViewRef.get().showToast("该课堂已创建，请\"加入课堂\"");
                    mView.get().createDiscussGroupRoomCallback(true, roomId, scheduleId);
                } else {
                    mView.get().showToast("创建课堂失败, 房间号：" + roomId + " err:" + errorCode + " msg:" + errorMessage);
                    mView.get().createDiscussGroupRoomCallback(false, roomId, scheduleId);
                }
            }
        });
    }


    public void setMemberJoin(List<String> userList) {
        for (String userId : userList) {
            model.getMemberByUserId(userId, true);
        }
        if (!isAttached()) return;
        mView.get().configOnlineMemberList(model.getMemberList());
    }

    public void setMemberQuit(List<String> userList) {
        for (String userId : userList) {
            BasicUserInfoBean memberByUserId = model.getMemberByUserId(userId, true);
            if (memberByUserId != null) {
                model.removeMemberByUserId(memberByUserId.ID);
            }
        }
        if (!isAttached()) return;
        mView.get().configOnlineMemberList(model.getMemberList());
    }

    @Override
    public List<BasicUserInfoBean> formatUserBeanList(List<BasicUserInfoBean> userBeanList) {
        if (userBeanList != null && !userBeanList.isEmpty()) {
            for (BasicUserInfoBean userBean : userBeanList) {
                model.notifyMember(userBean);
            }
        }
        return model.getMemberList();
    }

    @Override
    public void saveMember(BasicUserInfoBean coach) {
        model.notifyMember(coach);
    }

    private void formatChatMessageList(List<TIMMessage> messages) {
        if (messages == null || messages.isEmpty()) return;
        for (TIMMessage message : messages) {
            TIMElem element = message.getElement(0);
            if (element.getType() == TIMElemType.Text) {
                TIMTextElem textElem = (TIMTextElem) element;
                BasicUserInfoBean userBean = model.getMemberByUserId(message.getSender(), false);
                ChatMessageBean chatMessageBean = new ChatMessageBean(userBean, textElem.getText(), message);
                model.saveChatMessage(0, chatMessageBean);
            }
        }
        LiveDataBus.getInstance().with("ChatMessage", String.class).postValue("Load");
    }

    @Override
    public void sendTextMessage(final String userId, final String message) {
        TICManager.getInstance().sendTextMessage(userId, message, new TICManager.TICCallback<TIMMessage>() {
            @Override
            public void onSuccess(TIMMessage data) {
                BasicUserInfoBean userBean = model.getMemberByUserId(userId, true);
                ChatMessageBean chatMessageBean = new ChatMessageBean(userBean, "对[" + userId + "]说: " + message, data);
                model.saveChatMessage(chatMessageBean);
                LiveDataBus.getInstance().with("ChatMessage", String.class).postValue("Send");
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                if (!isAttached()) return;
                mView.get().showToast("发送消息失败" + errMsg);
            }
        });
    }

    @Override
    public List<BasicUserInfoBean> getMemberList() {
        return model.getMemberList();
    }

    @Override
    public void sendGroupTextMessage(final String message) {
        TICManager.getInstance().sendGroupTextMessage("", message, new TICManager.TICCallback<TIMMessage>() {
            @Override
            public void onSuccess(TIMMessage data) {
                BasicUserInfoBean userBean = model.getMemberByUserId(UserManager.getInstance().uid, true);
                ChatMessageBean chatMessageBean = new ChatMessageBean(userBean, message, data);
                model.saveChatMessage(chatMessageBean);
                LiveDataBus.getInstance().with("ChatMessage", String.class).postValue("Send");
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                if (!isAttached()) return;
                mView.get().showToast("发送群消息失败" + errMsg);

            }
        });
    }

    /**
     * 设置视频通话的视频参数：需要 TRTCSettingDialog 提供的分辨率、帧率和流畅模式等参数
     */
    private void setTRTCCloudParam() {

        // 大画面的编码器参数设置
        // 设置视频编码参数，包括分辨率、帧率、码率等等，这些编码参数来自于 TRTCSettingDialog 的设置
        // 注意（1）：不要在码率很低的情况下设置很高的分辨率，会出现较大的马赛克
        // 注意（2）：不要设置超过25FPS以上的帧率，因为电影才使用24FPS，我们一般推荐15FPS，这样能将更多的码率分配给画质
        TRTCCloudDef.TRTCVideoEncParam encParam = new TRTCCloudDef.TRTCVideoEncParam();
        // 分辨率
        encParam.videoResolution = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_640_360;
        // 分辨率模式（竖屏分辨率）
        encParam.videoResolutionMode = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_MODE_LANDSCAPE;
        // 帧率
        encParam.videoFps = 15;
        TICManager.getInstance().getTRTCCloud().setVideoEncoderParam(encParam);

        TRTCCloudDef.TRTCNetworkQosParam qosParam = new TRTCCloudDef.TRTCNetworkQosParam();
        // 服务端控制流量
        qosParam.controlMode = TRTCCloudDef.VIDEO_QOS_CONTROL_SERVER;
        // 优先流畅
        qosParam.preference = TRTCCloudDef.TRTC_VIDEO_QOS_PREFERENCE_SMOOTH;
        TICManager.getInstance().getTRTCCloud().setNetworkQosParam(qosParam);
        // 音量设置100
        TICManager.getInstance().getTRTCCloud().setMicVolumeOnMixing(100);

        TICManager.getInstance().getTRTCCloud().setLocalViewMirror(TRTCCloudDef.TRTC_VIDEO_MIRROR_TYPE_AUTO);

        TICManager.getInstance().getTRTCCloud().setPriorRemoteVideoStreamType(TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_SMALL);
        //美颜
        TICManager.getInstance().getTRTCCloud().setBeautyStyle(TRTCCloudDef.TRTC_BEAUTY_STYLE_NATURE, 4, 5, 5);
        // 开启本地音频采集
//            TICManager.getInstance().getTRTCCloud().enableCustomAudioCapture(true);
    }
}
